<?php
session_start();
if(!$_SESSION['logged']) 
	header("Location: ./index.php");
	
	
$processed = $_SESSION['processed'];
$completed = $_SESSION['completed'];
$files_to_be_packed = "";
$state = 0;
$type = ($_POST['format']);

foreach($_POST as $a => $key){
	if ($state == 1){
		$key = explode(".",$key); unset($key[sizeof($key)-1]); $key = implode(".",$key);
		if(file_exists($completed.$key.".".$type)) {
			$files_to_be_packed .= escapeshellarg($completed.$key.".".$type)." ";
		}
		 else if (file_exists($processed.$key.".".$type)){
			$files_to_be_packed .= escapeshellarg($processed.$key.".".$type)." ";
		}
		$state = 0;
	}
	else if ($key == 'on'){
		$state = 1;
	}
}

if(strlen($files_to_be_packed) == 0){
	header("Location: ./index.php");
}
// TODO: The downloaded package name is a random number. It could be something a bit more descriptive...
$rnd = rand(0,1000000);
$cmd = "zip -jc tmp/".$rnd.".zip ".$files_to_be_packed;
$filename = $rnd.".zip";
$filepath = "tmp/";

shell_exec($cmd);

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
@readfile($filepath.$filename);
?>
